﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Core.Model;
using PersonalHealth.Data.Model;
using System.IO;
using Microsoft.Win32;
using PersonHealth.View;

namespace PersonHealth
{
    /// <summary>
    /// ReportForm.xaml 的交互逻辑
    /// </summary>
    public partial class ReportForm : Page
    {

        IItem obj = null;
        ReportFormPage wbo = null;
        public ReportForm(IItem obj)
        {
            InitializeComponent();
            this.Unloaded += new RoutedEventHandler(ReportForm_Unloaded);
            if (obj != null)
            {
                this.obj = obj;
                title.Text = (obj as HealthReport).Title;
                string text = (obj as HealthReport).Text;
                //Stream stream = new MemoryStream(Encoding.Default.GetBytes(text));
                //webBrowser1.NavigateToStream(stream);
                wbo = new ReportFormPage(webBorder);
                WebBrowser wb = wbo.WebBrowser;
                Stream stream = new MemoryStream(Encoding.Default.GetBytes(text));
                wb.NavigateToStream(stream);
            }
            else
            {
                throw new ArgumentNullException();
            }
        }

        void ReportForm_Unloaded(object sender, RoutedEventArgs e)
        {
            if (wbo != null)
                wbo.Close();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            string extension = "doc";

            string selectedItem = "Word";

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = extension;
            dialog.Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, selectedItem);
            dialog.FileName = string.Format("{0}_{1}",AppData.User.Name , (obj as HealthReport).Title).Replace('/','_');
            dialog.FilterIndex = 1;

            if (dialog.ShowDialog() == true)
            {
                try
                {
                    using (Stream stream = dialog.OpenFile())
                    {

                        byte[] bs = Encoding.UTF8.GetBytes((obj as HealthReport).Text);
                        stream.Write(bs, 0, bs.Length);
                        stream.Flush();
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
    }
}
